package org.xxpay.pay.channel.fuwantong;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import org.xxpay.common.util.HtmlUtils;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service
public class FuwantongPaymentService extends BasePayment {

    private final static String logPrefix = "【福万通支付】";
    @Override
    public String getChannelName() {
        return FuwantongConfig.CHANNEL_NAME;
    }

    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder){
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder){
        JSONObject retObj = buildRetObj();
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, "没有订单查询接口");
        return retObj;
    }

    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder){
        FuwantongConfig config = new FuwantongConfig(getPayParam(payOrder));
        // 请求参数
        Map<String, Object> parameters = Maps.newHashMap();
        setParams(payOrder,config,parameters);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(parameters));
        // 将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);

        JSONObject retObj = new JSONObject();
        String payForm = HtmlUtils.form(config.getRequestUrl()+FuwantongConfig.REQ_PAY_URL_FIXX, HtmlUtils.POST, parameters);

        return buildPayResultOfForm(retObj, payOrder, payForm);
    }

    //设置请求参数
    private void setParams(PayOrder payOrder, FuwantongConfig config,Map<String,Object> params){
        params.put("openid", config.getAppId());
        params.put("mch_secret", config.getPublicKey());
        params.put("nonce_str", getRandomString(32));
        params.put("body", payOrder.getPayOrderId());
        params.put("out_trade_no", payOrder.getPayOrderId());
        params.put("total_fee", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        params.put("notify_url", payConfig.getNotifyUrl(getChannelName()));
        params.put("trade_type", config.getPayMode());
        params.put("device_info", "app");
        params.put("time_Stamp", System.currentTimeMillis()/1000);
        params.put("sign", getSign(params, config.getPrivateKey()));
    }

    //获取sign
    private String getSign(Map<String,Object> params,String key){
        String signTxt = SignUtils.parameterText(params);
        _log.info("{}待签名字符串：{}", logPrefix, signTxt+"&key="+key);
        String sign = SignUtils.MD5.createSign(signTxt, "&key="+key, SignUtils.CHARSET_UTF8).toUpperCase();
        return sign;
    }

    /**
     * 获取随机字符串
     * @param length
     * @return
     */
    private static String getRandomString(int length){
        String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            int number=random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
